Exercise
- Combine all elements of
df_list to one data frame. The
result should be only a single line of code.
do.call(rbind.data.frame, df_list)
do.call pass elements of df_list as
arguments to rbind. Itβs equivalent of
rbind(df_list[[1]], df_list[[2]], df_list[[3]], ....., df_list[[length of df_list]]).
- Fix each of the following common data frame subsetting errors:
mtcars[mtcars$cyl == 4, ]
mtcars[-c(1:4), ]
mtcars[mtcars$cyl <= 5, ]
mtcars[mtcars$cyl == 4 | mtcars$cyl == 6, ]
- What does
df[is.na(df)] <- 0 do
- replaces all
NAs with 0 but keeps the
dimensions.
- How would you randomly permute the columns of a data frame?
- Write a
while and a repeat loop doing the
same as
for(i in LETTERS[1:10]){
print(i)
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# while
i <- 0
while (i < 10) {
i = i + 1
print(LETTERS[i])
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# alternative
i <- 1
while (i < 11) {
print(LETTERS[i])
i = i + 1
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# repeat
i <- 0
repeat{
i = i + 1
print(LETTERS[i])
if (i > 9) {
break
}
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# alternative
i <- 1
repeat{
print(LETTERS[i])
i = i + 1
if (i > 10) {
break
}
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
- Write a
for loop doing the same as
count <- 0
repeat{
x <- sample(1:6, 1)
count <- count + 1
if(x == 6) break
}
print(count)
## [1] 21
for (i in 1:100) {
x <- sample(1:6, 1)
count <- i
if(x == 6) break
}
print(count)
## [1] 6
- note that \(n\) has to be high
enough
- What is the problem here?
- Curly braces are open and closed before the statement is passed to
the function
- What is the problem here? Can you debug it?
df will not be passed to the final call and
fast_lm is the wrong call
df <- mtcars
lin_mod <- function(df){
lm(y ~ . ,data = df)
}
simple_lin_mod <- function(data, y, x){
df <- data[ ,c(y, x)]
names(df) <- c("y", "x")
lin_mod(df)
}
simple_lin_mod(df, "mpg", "cyl")
##
## Call:
## lm(formula = y ~ ., data = df)
##
## Coefficients:
## (Intercept) x
## 37.885 -2.876